// pages/checkin/checkin.js
//这里因为图方便把数组渲染写进了getnowday里面，导致程序结构上有一些不完善，后续可以改进（拆分开来）
var app = getApp();
var serverDate = app.globalData.serverDate;
const getserverDate = app.getserverDate;
const db = wx.cloud.database();
const checkin1 = db.collection("checkin1");
const crecord = db.collection("crecord");
const class1 = db.collection("class1");
var latitude = 0;
var longitude = 0;
var accuracy = 0;
const latitudemax = 31.2105;
const latitudemin = 31.2098;
const prelameter = 111133.6;
const longitudemin = 121.318;
const longitudemax = 121.319;
const prelongmeter = 95210.3;
const phone = parseInt(app.globalData.phone);
var year=1;
var month=1;
var today=1;
var firstD=1;
var j=0;
var jm=0;
var checkinsuccess=false;
var checkinavailable=false;
var locationavailabe=false;
var total2=0;
var total5=0;

function judgelocation(){
  return new Promise((resolve,reject)=>{
    wx.getLocation({
      type: 'wgs84',
      isHighAccuracy: true,
      highAccuracyExpireTime: 5000,
      success: function (res) {
        latitude = res.latitude
        longitude = res.longitude
        accuracy = res.horizontalAccuracy
        console.log('成功')
      },
      fail: function(res){
        console.log(res);
        reject();
      }
    })
    if ((longitudemax-accuracy/prelongmeter<longitudemax)&&(longitudemax+accuracy/prelongmeter>longitudemin)&&(latitudemax-accuracy/prelameter<latitudemax)&&(latitudemax+accuracy/prelameter>latitudemin)){
      locationavailabe=true;
    }
    resolve();
  })
} 

Page({
  data: {
    dayData:['日','一','二','三','四','五','六',],
    year:'',  //年份
    month:'',  //月份
    allDays:[], //当前总共多少天,
    firstDay:'', //当月第一天星期几
    slotArr:[],  //占位数组(元素35个),
    Color1:[],   //#44e036，准时
    Color2:[],  //#FFF200，迟到
    Color3:[],  //#ED1C24，缺勤
    Color4:[],  //#C3C3C3，无需记录(无课)
    Color5:[],  //#99D9EA，请假
    record1:true,
    record2:false,
    record3:false,
    record4:false,
    record5:false,
    pagenotready:true,
    latelength:0,
    absencelength:0,
  },
  //初始化占位数组
  initSloatArr(){
    let copyArr=[]
    for(let i=0;i<42;i++){
      copyArr.push({
        text:''
      })
    }
    this.setData({
      slotArr:copyArr
    })
  },
  // 初始化年月
  initYearMonth(serverDate){
    this.setData({
      year:parseInt(serverDate.substring(0,4)),
      month:parseInt(serverDate.substring(5,7))//以字符串直接操作在加减会出错
    })
  },
  previousMonth(){
    if(this.data.month==1){
      this.setData({
        month:12,
        year:this.data.year-1
      })
      month=12;
      year=year-1;
    }else{
      this.setData({
        month:this.data.month-1
      })
      month=month-1
    }
    this.initSloatArr()
    this.getYMDays(this.data.year,this.data.month)
    this.getNowDay(this.data.year,this.data.month,1)
  },
  nextMonth(){
    if(this.data.month==12){
      this.setData({
        month:1,
        year:this.data.year+1
      })
      month=1;
      year=year+1;
    }else{
      this.setData({
        month:this.data.month+1
      })
      month=month+1;
    }
    this.initSloatArr()
    this.getYMDays(this.data.year,this.data.month)
    this.getNowDay(this.data.year,this.data.month,1)
  },
  //根据年月获取总共多少天
  getYMDays(year,month){
    var newDate = new Date(year,month,0);
    let allFlag=newDate.getDate()
    let allData=[]
    for(let i=1;i<=allFlag;i++){
      allData.push(i)
    }
    this.setData({
      allDays:allData
    })
  },
  //根据年月日判断是星期几&修改占位数组内容显示日历&渲染当前签到状况查看
  getNowDay(y,m,d){
    var serverDate = app.globalData.serverDate;
    var date=1;
    var date2=1;
    let newDate=`${y}-${m}-${d}`//字符串模板，抑音(非引号)+美元+大括号
    this.setData({
      firstDay:new Date(newDate).getDay(),
      pagenotready:true
    })
    firstD=new Date(newDate).getDay()
    //改占位数组--->当前月第一天为周几
    this.setData({
      [`slotArr[${this.data.firstDay}].text`]:1
    })
    //递增占位数组
    this.data.slotArr.map((item,index)=>{
        if(this.data.slotArr[index].text){
          this.setData({
            [`slotArr[${index+1}].text`]:this.data.slotArr[index].text+1
          })
        }
    })
    //删除占位数组中多出的日子
    let zArr=JSON.parse(JSON.stringify(this.data.slotArr))
    for(let i=this.data.allDays.length;i<this.data.slotArr.length;i++){
      if(this.data.slotArr[i].text>this.data.allDays.length){
        zArr.splice(i,15)
      }
    }
    //确定today值-当前需渲染到哪一天
    if ((year<parseInt(serverDate.substring(0,4)))  ||  ((year=parseInt(serverDate.substring(0,4)))&&(month<parseInt(serverDate.substring(5,7))))) {
      today=new Date(year,month,0).getDate()
    } else {
      if (year>parseInt(serverDate.substring(0,4))  ||  (year=parseInt(serverDate.substring(0,4)))&&(month>parseInt(serverDate.substring(5,7)))) {
        today=-1
      } else {
        today=parseInt(serverDate.substring(8,10))
      }
    }
    //渲染圆圈-获取总考勤情况，下载到数组
    let promises = [];
    for (let i=firstD;i<today+firstD;i++){
      zArr[i].cls='circle';
      promises.push(db.collection("checkin1").where({_id:18257509286}).get().then( res => {
        if (i-firstD<9) {
          j='0'+`${i-firstD+1}`;
        } else {
          j=`${i-firstD+1}`;
        }
        if (m<10) {
          jm='0'+`${m}`;
        } else {
          jm=`${m}`;
        }
        date=`${y}${jm}`+j+'A';
        date2=`${y}${jm}`+j+'P';
        zArr[i].topColor=res.data[0][date];
        zArr[i].bottomColor=res.data[0][date2];
      }));
    }
    Promise.all(promises).then(() => {
      this.setData({
        slotArr:zArr,
        pagenotready:false
      }) 
    })
  },
  //签到，上传请求到服务器
  checkin(serverDate){
    return new Promise((resolve,reject)=>{
      var hour=new Date(serverDate).getHours();
      var minute=new Date(serverDate).getMinutes();
      var w=new Date(serverDate).getDay();
      var phone = parseInt(app.globalData.phone);
      var y=`${year}`;
      if (month<10) {
        var m='0'+`${month}`
      } else {
        var m=`${month}`
      }
      if (today<10) {
        var d='0'+`${today}`
      } else {
        var d=`${today}`
      }
      if (hour<12) {
        db.collection("classtime1").where({_id:`${w}`+'A'}).get().then( res => {
          if (res.data.length>0) {
            var classid=res.data[0].class;
            var classn=res.data[0].class+'.0';
            var classm=res.data[0].class+'.1';
            var checkinhour=parseInt(res.data[0].startime.split(":")[0]);
            var checkinminute=parseInt(res.data[0].startime.split(":")[1]);
            //签到
            if (!(res.data[0].startime == null || res.data[0].startime === '')  &&  (hour*60+minute+16>checkinhour*60+checkinminute)) {
              checkin1.where({_id:phone}).get().then( res=> {
                if (res.data[0][y+m+d+'A'] != '#FFFFFF') {
                  checkinsuccess=true;
                  resolve();
                }
                if (locationavailabe){
                  if (hour*60+minute-2<checkinhour*60+checkinminute) {
                    wx.showToast({
                      title: '签到已成功',
                      icon: 'success',
                      duration: 3000,
                    })
                    checkin1.where({_id:phone}).update({
                      data: {
                      [[y+m+d+'A']] : '#44e036'  //准时
                    },
                    
                  })
                  } else if (hour*60+minute-17<checkinhour*60+checkinminute) {
                    wx.showToast({
                      title: '迟到啦以后早起',
                      image: '/assets/images/checkin/late.png',
                      duration: 3000,
                    })
                    checkin1.where({_id:phone}).update({
                      data: {
                      [[y+m+d+'A']] : '#FFF200'  //迟到
                      },
                    })
                    crecord.where({_id:phone}).update({
                      data: {
                        [[classn]] : db.command.inc(1)  //迟到
                      },
                    })
                    
                  } else {
                    wx.showToast({
                      title: '缺勤啦以后早睡',
                      image: '/assets/images/checkin/absence.png',
                      duration: 3000,
                    })
                    checkin1.where({_id:phone}).update({
                      data: {
                      [[y+m+d+'A']] : '#ED1C24'  //缺勤
                      },
                    })
                    crecord.where({_id:phone}).update({
                      data: {
                        [[classm]] : db.command.inc(1)  //缺勤
                      },
                    })
                    
                  }
                  this.getNowDay(this.data.year,this.data.month,1);
                  checkinsuccess=true;
                  checkinavailable=true;
                }
              })
            } else {
              checkinavailable=false;
              checkin1.where({_id:phone}).get().then( res=> {
                if (res.data[0][y+m+d+'A'] != '#FFFFFF') {
                  checkinsuccess=true;
                  resolve();
                }
              })
            }
            //签到后反馈该课程签到状况
            class1.where({_id:parseInt(classid)}).get().then( res=> {
              total2=Math.floor(0.2*res.data[0]['total'])
              total5=Math.floor(0.5*res.data[0]['total'])
              this.setData({
                total2:total2,
                total5:total5
              })
            })
            crecord.where({_id:phone}).get().then( res=> {
              var recordlate=res.data[0][classid][0];
              var recordabsence=res.data[0][classid][1];
              if (recordlate>13) {
                recordlate=13
              }
              if (recordabsence>total5) {
                recordabsence=total5
              }
              if (recordlate>0) {
                if (recordlate<4) {
                  this.setData({
                    record1: false,
                    record2: true,
                  })
                } else {
                  this.setData({
                    record1: false,
                    record3: true,
                  })
                }
              }
              if (recordabsence>0) {
                if (recordabsence<total2+1) {
                  this.setData({
                    record1: false,
                    record4: true,
                  })
                } else {
                  this.setData({
                    record1: false,
                    record5: true,
                  })
                }
                this.setData({
                  recordlate: recordlate,
                  recordabsence: recordabsence,
                })
              }
            })
          }
          resolve();
        })
      } else {
        db.collection("classtime1").where({_id:`${w}`+'P'}).get().then( res => {
          if (res.data.length>0) {
            var classid=res.data[0].class;
            var classn=res.data[0].class+'.0';
            var classm=res.data[0].class+'.1';
            var checkinhour=parseInt(res.data[0].startime.split(":")[0]);
            var checkinminute=parseInt(res.data[0].startime.split(":")[1]);
            if (!(res.data[0].startime == null || res.data[0].startime === '')  &&  (hour*60+minute+16>checkinhour*60+checkinminute)  &&  (hour*60+minute<checkinhour*60+checkinminute+180)) {
              checkin1.where({_id:phone}).get().then( res=> {
                if (res.data[0][y+m+d+'P'] != '#FFFFFF') {
                  checkinsuccess=true;
                  resolve();
                }
                if (locationavailabe){
                  if (hour*60+minute-2<checkinhour*60+checkinminute) {
                    wx.showToast({
                      title: '签到已成功',
                      icon: 'success',
                      duration: 3000,
                    })
                    checkin1.where({_id:phone}).update({
                      data: {
                      [[y+m+d+'P']] : '#44e036'  //准时
                      },
                    })
                  } else if (hour*60+minute-17<checkinhour*60+checkinminute) {
                    wx.showToast({
                      title: '迟到啦下次注意',
                      image: '/assets/images/checkin/late.png',
                      duration: 3000,
                    })
                    checkin1.where({_id:phone}).update({
                      data: {
                      [[y+m+d+'P']] : '#FFF200'  //迟到
                    },
                    })
                    crecord.where({_id:phone}).update({
                      data: {
                        [[classn]] : db.command.inc(1)  //迟到
                      },
                    })
                    
                  } else {
                    wx.showToast({
                      title: '缺勤啦下次注意',
                      image: '/assets/images/checkin/absence.png',
                      duration: 3000,
                    })
                    checkin1.where({_id:phone}).update({
                      data: {
                      [[y+m+d+'P']] : '#ED1C24'  //缺勤
                      },
                    })
                    crecord.where({_id:phone}).update({
                      data: {
                        [[classm]] : db.command.inc(1)  //缺勤
                      },
                    })
                    
                  }
                  this.getNowDay(this.data.year,this.data.month,1);
                  checkinsuccess=true;
                  checkinavailable=true;
                }
              })
            } else {
              checkinavailable=false;
              checkin1.where({_id:phone}).get().then( res=> {
                if (res.data[0][y+m+d+'P'] != '#FFFFFF') {
                  checkinsuccess=true;
                  resolve();
                }
              })
            }
            class1.where({_id:parseInt(classid)}).get().then( res=> {
              total2=Math.floor(0.2*res.data[0]['total'])
              total5=Math.floor(0.5*res.data[0]['total'])
              this.setData({
                total2:total2,
                total5:total5
              })
            })
            crecord.where({_id:phone}).get().then( res=> {
              var recordlate=res.data[0][classid][0];
              var recordabsence=res.data[0][classid][1];
              if (recordlate>13) {
                recordlate=13
              }
              if (recordabsence>total5) {
                recordabsence=total5
              }
              if (recordlate>0) {
                if (recordlate<4) {
                  this.setData({
                    record1: false,
                    record2: true,
                    latelength: Math.round(recordlate/3*100),
                  })
                } else {
                  this.setData({
                    record1: false,
                    record3: true,
                    latelength: 100,
                  })
                }
              }
              if (recordabsence>0) {
                console.log(recordabsence,res.data[0]['total'])
                if (recordabsence<Math.floor(0.2*res.data[0]['total'])+1) {
                  this.setData({
                    record1: false,
                    record4: true,
                    absencelength: Math.round(recordabsence/Math.floor(0.2*res.data[0]['total'])*100)
                  })
                } else {
                  this.setData({
                    record1: false,
                    record5: true,
                    absencelength: 100
                  })
                }
                this.setData({
                  recordlate: recordlate,
                  recordabsence: recordabsence,
                })
              }
            })
          }
          setTimeout(() => {
            resolve();
          }, 2000);
        })
      }
    })
  },
  //触摸签到按钮
  tapbottom(){
    getserverDate((serverDate)=>{
      judgelocation().then((res)=>{
        if (locationavailabe==false) {
          wx.showToast({
            title: '位置不符合',
            icon: 'error',
            duration: 3000,
          })
          return;
        } else {
          checkin(serverDate).then((res)=>{
            if (checkinavailable==false) {
              wx.showToast({
                title: '现在不可签到',
                icon: 'error',
                duration: 3000,
              })
            }
          })
        }
      }).catch((res)=>{
        wx.showToast({
          title: '获取位置失败',
          icon: 'error',
          duration: 3000,
        })
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    getserverDate((serverDate)=>{

      //云函数调用测试工具
      /* wx.cloud.callFunction({
        name: 'timer-checkin', //云函数的名字
        //data:{a:10,b:20}, //传参
        success: (res) => {
          console.log(res)
        } 
      }) */

      year=parseInt(serverDate.substring(0,4));
      month=parseInt(serverDate.substring(5,7));
      this.initYearMonth(serverDate);
      this.initSloatArr();
      this.getYMDays(this.data.year,this.data.month);
      this.getNowDay(this.data.year,this.data.month,1);
      judgelocation().then((res)=>{
          this.checkin(serverDate).then((res)=>{
            this.setData({checkinsuccess})//checkinsuccess
          })
      })
    })
  }
})